package com.lau.videoeffect.utils

import android.opengl.GLES20
import android.util.Log

class Program {

    companion object {
        private const val TAG = "PROGRAM"
    }

    val mId: Int

    constructor(vertexShader: String, fragmentShader: String) {

        val vs = createShader(GLES20.GL_VERTEX_SHADER, vertexShader)
        val fs = createShader(GLES20.GL_FRAGMENT_SHADER, fragmentShader)
        mId = GLES20.glCreateProgram()

        GLES20.glAttachShader(mId, vs)
        GLES20.glAttachShader(mId, fs)
        GLES20.glLinkProgram(mId)

        val log = GLES20.glGetProgramInfoLog(mId)
        if (log.isNotEmpty()) {
            Log.e(TAG, "Program log: $log")
        }

        GLES20.glDeleteShader(vs)
        GLES20.glDeleteShader(fs)

    }

    private fun createShader(type: Int, source: String): Int {
        val shader = GLES20.glCreateShader(type)
        GLES20.glShaderSource(shader, source)
        GLES20.glCompileShader(shader)
        val log = GLES20.glGetShaderInfoLog(shader)
        if (log.isNotEmpty()) {
            Log.e(TAG, "Shader log: $log")
        }
        return shader
    }

    fun getAttribLocation(name: String): Int {
        return GLES20.glGetAttribLocation(mId, name)
    }

    fun getUniformLocation(name: String): Int {
        return GLES20.glGetUniformLocation(mId, name)
    }

    fun use() {
        GLES20.glUseProgram(mId)
    }


}